package service

import (
	"bytes"
	"elastalert2-webhook/model" // 替换elastalert2-webhook为你的模块名
	"encoding/json"
	"fmt"
	"html/template"
	"io"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

func ProcessRequest(c *gin.Context) (model.AlertData, error) {
	var alertData model.AlertData

	bodyBytes, err := io.ReadAll(c.Request.Body)
	if err != nil {
		logrus.Errorf("Could not read request body: %v", err)
		return alertData, err
	}

	// 将请求体复制回以便再次读取
	c.Request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))

	// 打印原始 JSON 数据
	var rawData interface{}
	if err := json.Unmarshal(bodyBytes, &rawData); err != nil {
		logrus.Errorf("Could not decode JSON: %v", err)
		c.AbortWithStatus(http.StatusBadRequest)
		return alertData, err
	}
	decodedBytes, err := json.MarshalIndent(rawData, "", "  ")
	if err != nil {
		logrus.Errorf("Could not re-encode JSON: %v", err)
		c.AbortWithStatus(http.StatusInternalServerError)
		return alertData, err
	}
	fmt.Println("Received decoded JSON data:", string(decodedBytes))

	// 再次将请求体复制回以绑定到结构体
	c.Request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))

	if err := json.Unmarshal(bodyBytes, &alertData); err != nil {
		logrus.Errorf("Error binding JSON: %v", err)
		c.AbortWithStatus(http.StatusBadRequest)
		return alertData, err
	}

	return alertData, nil
}

func SendAlert(alertData model.AlertData) error {
	tmpl, err := template.ParseFiles("template.tmpl")
	if err != nil {
		return err
	}

	var tmplBytes bytes.Buffer
	if err := tmpl.Execute(&tmplBytes, alertData); err != nil {
		return err
	}

	newData := map[string]string{
		"text":     tmplBytes.String(),
		"username": "报警程序",
	}

	newDataBytes, err := json.Marshal(newData)
	if err != nil {
		return err
	}

	url := "https://mind.im30.net/api/hooks/ggwq89q7hfdrx8iiq4gzxuyubo"
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(newDataBytes))
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	return nil
}
